// api/middleware/auth.go
package middleware

import (
	"errors"
	"mygin/internal/services"
	"mygin/pkg/response"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
)

func JWTAuthMiddleware(authSvc services.AuthService) gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.GetHeader("Authorization")
		if tokenString == "" {
			c.JSON(http.StatusBadRequest, response.Fail(400, "missing auth token"))
			c.Abort() // 确保终止后续处理
			return
		}

		claims, err := authSvc.ValidateToken(tokenString)
		if err != nil {
			if errors.Is(err, jwt.ErrTokenExpired) {
				c.JSON(http.StatusBadRequest, response.Fail(400, "令牌已过期"))
			} else {
				c.JSON(http.StatusBadRequest, response.Fail(400, "无效的令牌"))

			}
			c.Abort() // 确保终止后续处理
			return
		}

		c.Set("username", claims.Subject)
		c.Set("userID", claims.ID)
		c.Next()
	}
}
